Python Code Example Handbook – Sample Script Coding Tutorial for Beginners
Hi! Welcome. If you are learning Python, then this article is for you. You will find a thorough description of Python syntax and lots of code examples to guide you during your coding journey.
What we will cover:
- Variable Definitions in Python
- Hello, World! Program in Python
- Data Types and Built-in Data Structures in Python
- Python Operators
- Conditionals in Python
- For Loops in Python
- While Loops in Python
- Nested Loops in Python
- Functions in Python
- Recursion in Python
- Exception Handling in Python
- Object-Oriented Programming in Python
- How to Work with Files in Python
- Import Statements in Python
- List and Dictionary Comprehension in Python
- and more...
Are you ready? Let's begin! 🔅
💡 Tip:throughout this article, I will use <>to indicate that this part of the syntax will be replaced by the element described by the text. For example, <var>means that this will be replaced by a variable when we write the code.
🔹 Variable Definitions in Python
The most basic building-block of any programming language is the concept of a variable, a name and place in memory that we reserve for a value.
In Python, we use this syntax to create a variable and assign a value to this variable:
<var_name> = <value>For example:
age = 56name = "Nora"color = "Blue"grades = [67, 100, 87, 56]If the name of a variable has more than one word, then the Style Guide for Python Code recommends separating words with an underscore "as necessary to improve readability."
For example:
my_list = [1, 2, 3, 4, 5]💡 Tip:The Style Guide for Python Code (PEP 8) has great suggestions that you should follow to write clean Python code.
Here's an interactive scrim to help you understand variable definitions in Python:
Note that this scrim and the others in this handbook were narrated by a member of the Scrimba team and have been added to illustrate some key Python concepts.
🔸 Hello, World! Program in Python
Before we start diving into the data types and data structures that you can use in Python, let's see how you can write your first Python program.
You just need to call the print()function and write "Hello, World!"within parentheses:
print("Hello, World!")You will see this message after running the program:
"Hello, World!"💡 Tip:Writing a "Hello, World!"program is a tradition in the developer community. Most developers start learning how to code by writing this program.
Great. You just wrote your first Python program. Now let's start learning about the data types and built-in data structures that you can use in Python.
🔹 Data Types and Built-in Data Structures in Python
We have several basic data types and built-in data structures that we can work with in our programs. Each one has its own particular applications. Let's see them in detail.
Numeric Data Types in Python: Integers, Floats, and Complex
These are the numeric types that you can work with in Python:
Integers
Integers are numbers without decimals. You can check if a number is an integer with the type()function. If the output is <class 'int'>, then the number is an integer.
For example:
>>> type(1)<class 'int'>>>> type(15)<class 'int'>>>> type(0)<class 'int'>>>> type(-46)<class 'int'>Floats
Floats are numbers with decimals. You can detect them visually by locating the decimal point. If we call type()to check the data type of these values, we will see this as the output:
<class 'float'>Here we have some examples:
>>> type(4.5)<class 'float'>>>> type(5.8)<class 'float'>>>> type(2342423424.3)<class 'float'>>>> type(4.0)<class 'float'>>>> type(0.0)<class 'float'>>>> type(-23.5)<class 'float'>Complex
Complex numbers have a real part and an imaginary part denoted with j. You can create complex numbers in Python with complex(). The first argument will be the real part and the second argument will be the imaginary part.
These are some examples:
>>> complex(4, 5)(4+5j)>>> complex(6, 8)(6+8j)>>> complex(3.4, 3.4)(3.4+3.4j)>>> complex(0, 0)0j>>> complex(5)(5+0j)>>> complex(0, 4)4jStrings in Python
Strings incredibly helpful in Python. They contain a sequence of characters and they are usually used to represent text in the code.
For example:
"Hello, World!"'Hello, World!'We can use both single quotes ''or double quotes ""to define a string. They are both valid and equivalent, but you should choose one of them and use it consistently throughout the program.
💡 Tip:Yes! You used a string when you wrote the "Hello, World!"program. Whenever you see a value surrounded by single or double quotes in Python, that is a string.
Strings can contain any character that we can type in our keyboard, including numbers, symbols, and other special characters.
For example:
"45678""[email protected]""#IlovePython"💡 Tip:Spaces are also counted as characters in a string.
Quotes Within Strings
If we define a string with double quotes "", then we can use single quotes within the string. For example:
"I'm 20 years old"If we define a string with single quotes '', then we can use double quotes within the string. For example:
'My favorite book is "Sense and Sensibility"'String Indexing
We can use indices to access the characters of a string in our Python program. An index is an integer that represents a specific position in the string. They are associated to the character at that position.
This is a diagram of the string "Hello":
String: H e l l oIndex: 0 1 2 3 4💡 Tip:Indices start from 0and they are incremented by 1for each character to the right.
For example:
>>> my_string = "Hello">>> my_string[0]'H'>>> my_string[1]'e'>>> my_string[2]'l'>>> my_string[3]'l'>>> my_string[4]'o'We can also use negative indices to access these characters:
>>> my_string = "Hello">>> my_string[-1]'o'>>> my_string[-2]'l'>>> my_string[-3]'l'>>> my_string[-4]'e'>>> my_string[-5]'H'💡 Tip:we commonly use -1to access the last character of a string.
String Slicing
We may also need to get a slice of a string or a subset of its characters. We can do so with string slicing.
This is the general syntax:
<string_variable>[start:stop:step]startis the index of the first character that will be included in the slice. By default, it's 0.
stopis the index of the last character in the slice (this character will notbe included). By default, it is the last character in the string (if we omit this value, the last character will also be included).stepis how much we are going to add to the current index to reach the next index.
We can specify two parameters to use the default value of step, which is 1. This will include all the characters between startand stop(not inclusive):
<string_variable>[start:stop]For example:
>>> freecodecamp = "freeCodeCamp">>> freecodecamp[2:8]'eeCode'>>> freecodecamp[0:3]'fre'>>> freecodecamp[0:4]'free'>>> freecodecamp[4:7]'Cod'>>> freecodecamp[4:8]'Code'>>> freecodecamp[8:11]'Cam'>>> freecodecamp[8:12]'Camp'>>> freecodecamp[8:13]'Camp'💡 Tip:Notice that if the value of a parameter goes beyond the valid range of indices, the slice will still be presented. This is how the creators of Python implemented this feature of string slicing.
If we customize the step, we will "jump" from one index to the next according to this value.
For example:
>>> freecodecamp = "freeCodeCamp">>> freecodecamp[0:9:2]'feCdC'>>> freecodecamp[2:10:3]'eoC'>>> freecodecamp[1:12:4]'roa'>>> freecodecamp[4:8:2]'Cd'>>> freecodecamp[3:9:2]'eoe'>>> freecodecamp[1:10:5]'rd'We can also use a negativestep to go from right to left:
>>> freecodecamp = "freeCodeCamp">>> freecodecamp[10:2:-1]'maCedoCe'>>> freecodecamp[11:4:-2]'paeo'>>> freecodecamp[5:2:-4]'o'And we can omit a parameter to use its default value. We just have to include the corresponding colon (:) if we omit start, stop, or both:
>>> freecodecamp = "freeCodeCamp"# Default start and step>>> freecodecamp[:8]'freeCode'# Default end and step>>> freecodecamp[4:]'CodeCamp'# Default start>>> freecodecamp[:8:2]'feCd'# Default stop>>> freecodecamp[4::3]'Cem'# Default start and stop>>> freecodecamp[::-2]'paeoer'# Default start and stop>>> freecodecamp[::-1]'pmaCedoCeerf'💡 Tip:The last example is one of the most common ways to reverse a string.
f-Strings
In Python 3.6 and more recent versions, we can use a type of string called f-string that helps us format our strings much more easily.
To define an f-string, we just add an fbefore the single or double quotes. Then, within the string, we surround the variables or expressions with curly braces { }. This replaces their value in the string when we run the program.
For example:
first_name = "Nora"favorite_language = "Python"print(f"Hi, I'm { first_name}. I'm learning { favorite_language}.")The output is:
Hi, I'm Nora. I'm learning Python.Here we have an example where we calculate the value of an expression and replace the result in the string:
value = 5print(f"{ value} multiplied by 2 is: { value * 2}")The values are replaced in the output:
5 multiplied by 2 is: 10We can also call methods within the curly braces and the value returned will be replaced in the string when we run the program:
freecodecamp = "FREECODECAMP"print(f"{ freecodecamp.lower()}")The output is:
freecodecampString Methods
Strings have methods, which represent common functionality that has been implemented by Python developers, so we can use it in our programs directly. They are very helpful to perform common operations.
This is the general syntax to call a string method:
<string_variable>.<method_name>(<arguments>)For example:
>>> freecodecamp = "freeCodeCamp">>> freecodecamp.capitalize()'Freecodecamp'>>> freecodecamp.count("C")2>>> freecodecamp.find("e")2>>> freecodecamp.index("p")11>>> freecodecamp.isalnum()True>>> freecodecamp.isalpha()True>>> freecodecamp.isdecimal()False>>> freecodecamp.isdigit()False>>> freecodecamp.isidentifier()True>>> freecodecamp.islower()False>>> freecodecamp.isnumeric()False>>> freecodecamp.isprintable()True>>> freecodecamp.isspace()False>>> freecodecamp.istitle()False>>> freecodecamp.isupper()False>>> freecodecamp.lower()'freecodecamp'>>> freecodecamp.lstrip("f")'reeCodeCamp'>>> freecodecamp.rstrip("p")'freeCodeCam'>>> freecodecamp.replace("e", "a")'fraaCodaCamp'>>> freecodecamp.split("C")['free', 'ode', 'amp']>>> freecodecamp.swapcase()'FREEcODEcAMP'>>> freecodecamp.title()'Freecodecamp'>>> freecodecamp.upper()'FREECODECAMP'To learn more about Python methods, I would recommend reading this article from the Python documentation.
💡 Tip:All string methods return copies of the string. They do not modify the string because strings are immutable in Python.
Booleans in Python
Boolean values are Trueand Falsein Python. They must start with an uppercase letter to be recognized as a boolean value.
For example:
>>> type(True)<class 'bool'>>>> type(False)<class 'bool'>If we write them in lowercase, we will get an error:
>>> type(true)Traceback (most recent call last): File "<pyshell#92>", line 1, in <module> type(true)NameError: name 'true' is not defined>>> type(false)Traceback (most recent call last): File "<pyshell#93>", line 1, in <module> type(false)NameError: name 'false' is not definedLists in Python
Now that we've covered the basic data types in Python, let's start covering the built-in data structures. First, we have lists.
To define a list, we use square brackets []with the elements separated by a comma.
💡 Tip:It's recommended to add a space after each comma to make the code more readable.
For example, here we have examples of lists:
[1, 2, 3, 4, 5]["a", "b", "c", "d"][3.4, 2.4, 2.6, 3.5]Lists can contain values of different data types, so this would be a valid list in Python:
[1, "Emily", 3.4]We can also assign a list to a variable:
my_list = [1, 2, 3, 4, 5]letters = ["a", "b", "c", "d"]Nested Lists
Lists can contain values of any data type, even other lists. These inner lists are called nested lists.
[[1, 2, 3], [4, 5, 6]]In this example, [1, 2, 3]and [4, 5, 6]are nested lists.
Here we have other valid examples:
[["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]][1, [2, 3, 4], [5, 6, 7], 3.4]We can access the nested lists using their corresponding index:
>>> my_list = [[1, 2, 3], [4, 5, 6]]>>> my_list[0][1, 2, 3]>>> my_list[1][4, 5, 6]Nested lists could be used to represent, for example, the structure of a simple 2D game board where each number could represent a different element or tile:
# Sample Board where: # 0 = Empty tile# 1 = Coin# 2 = Enemy# 3 = Goalboard = [[0, 0, 1], [0, 2, 0], [1, 0, 3]]List Length
We can use the len()function to get the length of a list (the number of elements it contains).
For example:
>>> my_list = [1, 2, 3, 4]>>> len(my_list)4Update a Value in a List
We can update the value at a particular index with this syntax:
<list_variable>[<index>] = <value>For example:
>>> letters = ["a", "b", "c", "d"]>>> letters[0] = "z">>> letters['z', 'b', 'c', 'd']Add a Value to a List
We can add a new value to the end of a list with the .append()method.
For example:
>>> my_list = [1, 2, 3, 4]>>> my_list.append(5)>>> my_list[1, 2, 3, 4, 5]Remove a Value from a List
We can remove a value from a list with the .remove()method.
For example:
>>> my_list = [1, 2, 3, 4]>>> my_list.remove(3)>>> my_list[1, 2, 4]💡 Tip:This will only remove the first occurrence of the element. For example, if we try to remove the number 3 from a list that has two number 3s, the second number will not be removed:
>>> my_list = [1, 2, 3, 3, 4]>>> my_list.remove(3)>>> my_list[1, 2, 3, 4]List Indexing
We can index a list just like we index strings, with indices that start from 0:
>>> letters = ["a", "b", "c", "d"]>>> letters[0]'a'>>> letters[1]'b'>>> letters[2]'c'>>> letters[3]'d'List Slicing
We can also get a slice of a list using the same syntax that we used with strings and we can omit the parameters to use their default values. Now, instead of adding characters to the slice, we will be adding the elements of the list.
<list_variable>[start:stop:step]For example:
>>> my_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]>>> my_list[2:6:2]['c', 'e']>>> my_list[2:8]['c', 'd', 'e', 'f', 'g', 'h']>>> my_list[1:10]['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']>>> my_list[4:8:2]['e', 'g']>>> my_list[::-1]['i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']>>> my_list[::-2]['i', 'g', 'e', 'c', 'a']>>> my_list[8:1:-1]['i', 'h', 'g', 'f', 'e', 'd', 'c']List Methods
Python also has list methods already implemented to help us perform common list operations. Here are some examples of the most commonly used list methods:
>>> my_list = [1, 2, 3, 3, 4]>>> my_list.append(5)>>> my_list[1, 2, 3, 3, 4, 5]>>> my_list.extend([6, 7, 8])>>> my_list[1, 2, 3, 3, 4, 5, 6, 7, 8]>>> my_list.insert(2, 15)>>> my_list[1, 2, 15, 3, 3, 4, 5, 6, 7, 8, 2, 2]>>> my_list.remove(2)>>> my_list[1, 15, 3, 3, 4, 5, 6, 7, 8, 2, 2]>>> my_list.pop()2>>> my_list.index(6)6>>> my_list.count(2)1>>> my_list.sort()>>> my_list[1, 2, 3, 3, 4, 5, 6, 7, 8, 15]>>> my_list.reverse()>>> my_list[15, 8, 7, 6, 5, 4, 3, 3, 2, 1]>>> my_list.clear()>>> my_list[]To learn more about list methods, I would recommend reading this article from the Python documentation.
Here's an interactive scrim to help you learn more about lists in Python:
Tuples in Python
To define a tuple in Python, we use parentheses ()and separate the elements with a comma. It is recommended to add a space after each comma to make the code more readable.
(1, 2, 3, 4, 5)("a", "b", "c", "d")(3.4, 2.4, 2.6, 3.5)We can assign tuples to variables:
my_tuple = (1, 2, 3, 4, 5)Tuple Indexing
We can access each element of a tuple with its corresponding index:
>>> my_tuple = (1, 2, 3, 4)>>> my_tuple[0]1>>> my_tuple[1]2>>> my_tuple[2]3>>> my_tuple[3]4We can also use negative indices:
>>> my_tuple = (1, 2, 3, 4)>>> my_tuple[-1]4>>> my_tuple[-2]3>>> my_tuple[-3]2>>> my_tuple[-4]1Tuple Length
To find the length of a tuple, we use the len()function, passing the tuple as argument:
>>> my_tuple = (1, 2, 3, 4)>>> len(my_tuple)4Nested Tuples
Tuples can contain values of any data type, even lists and other tuples. These inner tuples are called nested tuples.
([1, 2, 3], (4, 5, 6))In this example, we have a nested tuple (4, 5, 6)and a list. You can access these nested data structures with their corresponding index.
For example:
>>> my_tuple = ([1, 2, 3], (4, 5, 6))>>> my_tuple[0][1, 2, 3]>>> my_tuple[1](4, 5, 6)Tuple Slicing
We can slice a tuple just like we sliced lists and strings. The same principle and rules apply.
This is the general syntax:
<tuple_variable>[start:stop:step]For example:
>>> my_tuple = (4, 5, 6, 7, 8, 9, 10)>>> my_tuple[3:8](7, 8, 9, 10)>>> my_tuple[2:9:2](6, 8, 10)>>> my_tuple[:8](4, 5, 6, 7, 8, 9, 10)>>> my_tuple[:6](4, 5, 6, 7, 8, 9)>>> my_tuple[:4](4, 5, 6, 7)>>> my_tuple[3:](7, 8, 9, 10)>>> my_tuple[2:5:2](6, 8)>>> my_tuple[::2](4, 6, 8, 10)>>> my_tuple[::-1](10, 9, 8, 7, 6, 5, 4)>>> my_tuple[4:1:-1](8, 7, 6)Tuple Methods
There are two built-in tuple methods in Python:
>>> my_tuple = (4, 4, 5, 6, 6, 7, 8, 9, 10)>>> my_tuple.count(6)2>>> my_tuple.index(7)5💡 Tip:tuples are immutable. They cannot be modified, so we can't add, update, or remove elements from the tuple. If we need to do so, then we need to create a new copy of the tuple.
Tuple Assignment
In Python, we have a really cool feature called Tuple Assignment. With this type of assignment, we can assign values to multiple variables on the same line.
The values are assigned to their corresponding variables in the order that they appear. For example, in a, b = 1, 2the value 1is assigned to the variable aand the value 2is assigned to the variable b.
For example:
# Tuple Assignment>>> a, b = 1, 2>>> a1>>> b2💡 Tip:Tuple assignment is commonly used to swap the values of two variables:
>>> a = 1>>> b = 2# Swap the values>>> a, b = b, a>>> a2>>> b1Dictionaries in Python
Now let's start diving into dictionaries. This built-in data structure lets us create pairs of values where one value is associated with another one.
To define a dictionary in Python, we use curly brackets { }with the key-value pairs separated by a comma.
The key is separated from the value with a colon :, like this:
{ "a": 1, "b": 2, "c"; 3}You can assign the dictionary to a variable:
my_dict = { "a": 1, "b": 2, "c"; 3}The keys of a dictionary must be of an immutable data type. For example, they can be strings, numbers, or tuples but not lists since lists are mutable.
- Strings:
{ "City 1": 456, "City 2": 577, "City 3": 678} - Numbers:
{ 1: "Move Left", 2: "Move Right", 3: "Move Up", 4: "Move Down"} - Tuples:
{ (0, 0): "Start", (2, 4): "Goal"}
The values of a dictionary can be of any data type, so we can assign strings, numbers, lists, tuple, sets, and even other dictionaries as the values. Here we have some examples:
{ "product_id": 4556, "ingredients": ["tomato", "cheese", "mushrooms"], "price": 10.67}{ "product_id": 4556, "ingredients": ("tomato", "cheese", "mushrooms"), "price": 10.67}{ "id": 567, "name": "Emily", "grades": { "Mathematics": 80, "Biology": 74, "English": 97}}Dictionary Length
To get the number of key-value pairs, we use the len()function:
>>> my_dict = { "a": 1, "b": 2, "c": 3, "d": 4}>>> len(my_dict)4Get a Value in a Dictionary
To get a value in a dictionary, we use its key with this syntax:
<variable_with_dictionary>[<key>]This expression will be replaced by the value that corresponds to the key.
For example:
my_dict = { "a": 1, "b": 2, "c": 3, "d": 4}print(my_dict["a"])The output is the value associated to "a":
1Update a Value in a Dictionary
To update the value associated with an existing key, we use the same syntax but now we add an assignment operator and the value:
<variable_with_dictionary>[<key>] = <value>For example:
>>> my_dict = { "a": 1, "b": 2, "c": 3, "d": 4}>>> my_dict["b"] = 6Now the dictionary is:
{ 'a': 1, 'b': 6, 'c': 3, 'd': 4}Add a Key-Value Pair to a Dictionary
The keys of a dictionary have to be unique. To add a new key-value pair we use the same syntax that we use to update a value, but now the key has to be new.
<variable_with_dictionary>[<new_key>] = <value>For example:
>>> my_dict = { "a": 1, "b": 2, "c": 3, "d": 4}>>> my_dict["e"] = 5Now the dictionary has a new key-value pair:
{ 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}Delete a Key-Value Pair in a Dictionary
To delete a key-value pair, we use the delstatement:
del <dictionary_variable>[<key>]For example:
>>> my_dict = { "a": 1, "b": 2, "c": 3, "d": 4}>>> del my_dict["c"]Now the dictionary is:
{ 'a': 1, 'b': 2, 'd': 4}Dictionary Methods
These are some examples of the most commonly used dictionary methods:
>>> my_dict = { "a": 1, "b": 2, "c": 3, "d": 4}>>> my_dict.get("c")3>>> my_dict.items()dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)])>>> my_dict.keys()dict_keys(['a', 'b', 'c', 'd'])>>> my_dict.pop("d")4>>> my_dict.popitem()('c', 3)>>> my_dict.setdefault("a", 15)1>>> my_dict{ 'a': 1, 'b': 2}>>> my_dict.setdefault("f", 25)25>>> my_dict{ 'a': 1, 'b': 2, 'f': 25}>>> my_dict.update({ "c": 3, "d": 4, "e": 5})>>> my_dict.values()dict_values([1, 2, 25, 3, 4, 5])>>> my_dict.clear()>>> my_dict{ }To learn more about dictionary methods, I recommend reading this article from the documentation.
And here's an interactive scrim to help you learn more about data types in Python:
🔸 Python Operators
Great. Now you know the syntax of the basic data types and built-in data structures in Python, so let's start diving into operators in Python. They are essential to perform operations and to form expressions.
Arithmetic Operators in Python
These operators are:
Addition: +
>>> 5 + 611>>> 0 + 66>>> 3.4 + 5.79.1>>> "Hello" + ", " + "World"'Hello, World'>>> True + False1💡 Tip:The last two examples are curious, right? This operator behaves differently based on the data type of the operands.
When they are strings, this operator concatenates the strings and when they are Boolean values, it performs a particular operation.
In Python, Trueis equivalent to 1and Falseis equivalent to 0. This is why the result is 1 + 0 = 1
Subtraction: -
>>> 5 - 6-1>>> 10 - 37>>> 5 - 6-1>>> 4.5 - 5.6 - 2.3-3.3999999999999995>>> 4.5 - 7-2.5>>> - 7.8 - 6.2-14.0Multiplication: *
>>> 5 * 630>>> 6 * 742>>> 10 * 1001000>>> 4 * 00>>> 3.4 *6.823.119999999999997>>> 4 * (-6)-24>>> (-6) * (-8)48>>> "Hello" * 4'HelloHelloHelloHello'>>> "Hello" * 0''>>> "Hello" * -1''💡 Tip:you can "multiply" a string by an integer to repeat the string a given number of times.
Exponentiation: **
>>> 6 ** 81679616>>> 5 ** 225>>> 4 ** 01>>> 16 ** (1/2)4.0>>> 16 ** (0.5)4.0>>> 125 ** (1/3)4.999999999999999>>> 4.5 ** 2.331.7971929089206>>> 3 ** (-1)0.3333333333333333Division: /
>>> 25 / 55.0>>> 3 / 60.5>>> 0 / 50.0>>> 2467 / 46730.5279263856195163>>> 1 / 20.5>>> 4.5 / 3.51.2857142857142858>>> 6 / 70.8571428571428571>>> -3 / -40.75>>> 3 / -4-0.75>>> -3 / 4-0.75💡 Tip:this operator returns a floatas the result, even if the decimal part is .0
If you try to divide by 0, you will get a ZeroDivisionError:
>>> 5 / 0Traceback (most recent call last): File "<pyshell#109>", line 1, in <module> 5 / 0ZeroDivisionError: division by zeroInteger Division: //
This operator returns an integer if the operands are integers. If they are floats, the result will be a float with .0as the decimal part because it truncates the decimal part.
>>> 5 // 60>>> 8 // 24>>> -4 // -50>>> -5 // 8-1>>> 0 // 50>>> 156773 // 356440Modulo: %
>>> 1 % 51>>> 2 % 52>>> 3 % 53>>> 4 % 54>>> 5 % 50>>> 5 % 85>>> 3 % 10>>> 15 % 30>>> 17 % 81>>> 2568 % 40>>> 245 % 155>>> 0 % 60>>> 3.5 % 2.41.1>>> 6.7 % -7.8-1.0999999999999996>>> 2.3 % 7.52.3Comparison Operators
These operators are:
- Greater than:
> - Greater than or equal to:
>= - Less than:
< - Less than or equal to:
<= - Equal to:
== - Not Equal to:
!=
These comparison operators make expressions that evaluate to either Trueor False. Here we have are some examples:
>>> 5 > 6False>>> 10 > 8True>>> 8 > 8False>>> 8 >= 5True>>> 8 >= 8True>>> 5 < 6True>>> 10 < 8False>>> 8 < 8False>>> 8 <= 5False>>> 8 <= 8True>>> 8 <= 10True>>> 56 == 56True>>> 56 == 78False>>> 34 != 59True>>> 67 != 67FalseWe can also use them to compare strings based on their alphabetical order:
>>> "Hello" > "World"False>>> "Hello" >= "World"False>>> "Hello" < "World"True>>> "Hello" <= "World"True>>> "Hello" == "World"False>>> "Hello" != "World"TrueWe typically use them to compare the values of two or more variables:
>>> a = 1>>> b = 2>>> a < bTrue>>> a <= bTrue>>> a > bFalse>>> a >= bFalse>>> a == bFalse>>> a != bTrue💡 Tip:notice that the comparison operator is ==while the assignment operator is =. Their effect is different. ==returns Trueor Falsewhile =assigns a value to a variable.
Comparison Operator Chaining
In Python, we can use something called "comparison operator chaining" in which we chain the comparison operators to make more than one comparison more concisely.
For example, this checks if ais less than band if bis less than c:
a < b < cHere we have some examples:
>>> a = 1>>> b = 2>>> c = 3>>> a < b < cTrue>>> a > b > cFalse>>> a <= b <= cTrue>>> a >= b >= cFalse>>> a >= b > cFalse>>> a <= b < cTrueLogical Operators
There are three logical operators in Python: and, or, and not. Each one of these operators has its own truth table and they are essential to work with conditionals.
The andoperator:
>>> True and TrueTrue>>> True and FalseFalse>>> False and TrueFalse>>> False and FalseFalseThe oroperator:
>>> True or TrueTrue>>> True or FalseTrue>>> False or TrueTrue>>> False or FalseFalseThe notoperator:
>>> not TrueFalse>>> not FalseTrueThese operator are used to form more complex expressions that combine different operators and variables.
For example:
>>> a = 6>>> b = 3>>> a < 6 or b > 2True>>> a >= 3 and b >= 1True>>> (a + b) == 9 and b > 1True>>> ((a % 3) < 2) and ((a + b) == 3)FalseAssignment Operators
Assignment operators are used to assign a value to a variable.
They are: =, +=, -=, *=, %=, /=, //=, **=
- The
=operator assigns the value to the variable. - The other operators perform an operation with the current value of the variable and the new value and assigns the result to the same variable.
For example:
>>> x = 3>>> x3>>> x += 15>>> x18>>> x -= 2>>> x16>>> x *= 2>>> x32>>> x %= 5>>> x2>>> x /= 1>>> x2.0>>> x //= 2>>> x1.0>>> x **= 5>>> x1.0💡 Tips:these operators perform bitwise operations before assigning the result to the variable: &=, |=, ^=, >>=, <<=.
Membership Operators
You can check if an element is in a sequence or not with the operators: inand not in. The result will be either Trueor False.
For example:
>>> 5 in [1, 2, 3, 4, 5]True>>> 8 in [1, 2, 3, 4, 5]False>>> 5 in (1, 2, 3, 4, 5)True>>> 8 in (1, 2, 3, 4, 5)False>>> "a" in { "a": 1, "b": 2}True>>> "c" in { "a": 1, "b": 2}False>>> "h" in "Hello"False>>> "H" in "Hello"True>>> 5 not in [1, 2, 3, 4, 5]False>>> 8 not in (1, 2, 3, 4, 5)True>>> "a" not in { "a": 1, "b": 2}False>>> "c" not in { "a": 1, "b": 2}True>>> "h" not in "Hello"True>>> "H" not in "Hello"FalseWe typically use them with variables that store sequences, like in this example:
>>> message = "Hello, World!">>> "e" in messageTrue🔹 Conditionals in Python
Now let's see how we can write conditionals to make certain parts of our code run (or not) based on whether a condition is Trueor False.
ifstatements in Python
This is the syntax of a basic ifstatement:
if <condition>: <code>If the condition is True, the code will run. Else, if it's False, the code will not run.
💡 Tip:there is a colon (:) at the end of the first line and the code is indented. This is essential in Python to make the code belong to the conditional.
Here we have some examples:
False Condition
x = 5if x > 9: print("Hello, World!")The condition is x > 9and the code is print("Hello, World!").
In this case, the condition is False, so there is no output.
True Condition
Here we have another example. Now the condition is True:
color = "Blue"if color == "Blue": print("This is my favorite color")The output is:
"This is my favorite color"Code After the Conditional
Here we have an example with code that runs after the conditional has been completed. Notice that the last line is not indented, which means that it doesn't belong to the conditional.
x = 5if x > 9: print("Hello!")print("End")In this example, the condition x > 9is False, so the first print statement doesn't run but the last print statement runs because it is not part of the conditional, so the output is:
EndHowever, if the condition is True, like in this example:
x = 15if x > 9: print("Hello!")print("End")The output will be:
Hello!EndExamples of Conditionals
This is another example of a conditional:
favorite_season = "Summer"if favorite_season == "Summer": print("That is my favorite season too!")In this case, the output will be:
That is my favorite season too!But if we change the value of favorite_season:
favorite_season = "Winter"if favorite_season == "Summer": print("That is my favorite season too!")There will be no output because the condition will be False.
if/elsestatements in Python
We can add an elseclause to the conditional if we need to specify what should happen when the condition is False.
This is the general syntax:
if <condition>: <code>else: <code>💡 Tip:notice that the two code blocks are indented (ifand else). This is essential for Python to be able to differentiate between the code that belongs to the main program and the code that belongs to the conditional.
Let's see an example with the elseclause:
True Condition
x = 15if x > 9: print("Hello!")else: print("Bye!")print("End")The output is:
Hello!EndWhen the condition of the ifclause is True, this clause runs. The elseclause doesn't run.
False Condition
Now the elseclause runs because the condition is False.
x = 5if x > 9: print("Hello!")else: print("Bye!")print("End")Now the output is:
Bye!Endif/elif/elsestatements in Python
To customize our conditionals even further, we can add one or more elifclauses to check and handle multiple conditions. Only the code of the first condition that evaluates to Truewill run.
💡 Tip:elifhas to be written after ifand before else.
First Condition True
x = 5if x < 9: print("Hello!")elif x < 15: print("It's great to see you")else: print("Bye!")print("End")We have two conditions x < 9and x < 15. Only the code block from the first condition that is Truefrom top to bottom will be executed.
In this case, the output is:
Hello!EndBecause the first condition is True: x < 9.
Second Condition True
If the first condition is False, then the second condition will be checked.
In this example, the first condition x < 9is Falsebut the second condition x < 15is True, so the code that belongs to this clause will run.
x = 13if x < 9: print("Hello!")elif x < 15: print("It's great to see you")else: print("Bye!")print("End")The output is:
It's great to see youEndAll Conditions are False
If all conditions all False, then the elseclause will run:
x = 25if x < 9: print("Hello!")elif x < 15: print("It's great to see you")else: print("Bye!")print("End")The output will be:
Bye!EndMultiple elif Clauses
We can add as many elifclauses as needed. This is an example of a conditional with two elifclauses:
if favorite_season == "Winter": print("That is my favorite season too")elif favorite_season == "Summer": print("Summer is amazing")elif favorite_season == "Spring": print("I love spring")else: print("Fall is my mom's favorite season")Each condition will be checked and only the code block of the first condition that evaluates to Truewill run. If none of them are True, the elseclause will run.
Here's an interactive scrim to help you learn more about conditionals in Python:
🔸 For Loops in Python
Now you know how to write conditionals in Python, so let's start diving into loops. For loops are amazing programming structures that you can use to repeat a code block a specific number of times.
This is the basic syntax to write a for loop in Python:
for <loop_variable> in <iterable>: <code>The iterable can be a list, tuple, dictionary, string, the sequence returned by range, a file, or any other type of iterable in Python. We will start with range().
The range()function in Python
This function returns a sequence of integers that we can use to determine how many iterations (repetitions) of the loop will be completed. The loop will complete one iteration per integer.
💡 Tip:Each integer is assigned to the loop variable one at a time per iteration.
This is the general syntax to write a for loop with range():
for <loop_variable> in range(<start>, <stop>, <step>): <code>As you can see, the range function has three parameters:
start: where the sequence of integers will start. By default, it's0.stop: where the sequence of integers will stop (without including this value).step: the value that will be added to each element to get the next element in the sequence. By default, it's1.
You can pass 1, 2, or 3 arguments to range():
- With 1 argument, the value is assigned to the
stopparameter and the default values for the other two parameters are used. - With 2 arguments, the values are assigned to the
startandstopparameters and the default value forstepis used. - With 3 arguments, the values are assigned to the
start,stop, andstepparameters (in order).
Here we have some examples with one parameter:
for i in range(5): print(i)Output:
01234💡 Tip:the loop variable is updated automatically.
>>> for j in range(15): print(j * 2)Output:
0246810121416182022242628In the example below, we repeat a string as many times as indicated by the value of the loop variable:
>>> for num in range(8): print("Hello" * num)Output:
HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloWe can also use for loops with built-in data structures such as lists:
>>> my_list = ["a", "b", "c", "d"]>>> for i in range(len(my_list)): print(my_list[i])Output:
abcd💡 Tip:when you use range(len(<seq>)), you get a sequence of numbers that goes from 0up to len(<seq>)-1. This represents the sequence of valid indices.
These are some examples with two parameters:
>>> for i in range(2, 10): print(i)Output:
23456789Code:
>>> for j in range(2, 5): print("Python" * j)Output:
PythonPythonPythonPythonPythonPythonPythonPythonPythonCode:
>>> my_list = ["a", "b", "c", "d"]>>> for i in range(2, len(my_list)): print(my_list[i])Output:
cdCode:
>>> my_list = ["a", "b", "c", "d"]>>> for i in range(2, len(my_list)-1): my_list[i] *= iNow the list is: ['a', 'b', 'cc', 'd']
These are some examples with three parameters:
>>> for i in range(3, 16, 2): print(i)Output:
3579111315Code:
>>> for j in range(10, 5, -1): print(j)Output:
109876Code:
>>> my_list = ["a", "b", "c", "d", "e", "f", "g"]>>> for i in range(len(my_list)-1, 2, -1): print(my_list[i])Output:
gfedHow to Iterate over Iterables in Python
We can iterate directly over iterables such as lists, tuples, dictionaries, strings, and files using for loops. We will get each one of their elements one at a time per iteration. This is very helpful to work with them directly.
Let's see some examples:
Iterate Over a String
If we iterate over a string, its characters will be assigned to the loop variable one by one (including spaces and symbols).
>>> message = "Hello, World!">>> for char in message: print(char)Hello,World!We can also iterate over modified copies of the string by calling a string method where we specify the iterable in the for loop. This will assign the copy of the string as the iterable that will be used for the iterations, like this:
>>> word = "Hello">>> for char in word.lower(): # calling the string method print(char)hello>>> word = "Hello">>> for char in word.upper(): # calling the string method print(char)HELLOIterate Over Lists and Tuples
>>> my_list = [2, 3, 4, 5]>>> for num in my_list: print(num)The output is:
2345Code:
>>> my_list = (2, 3, 4, 5)>>> for num in my_list: if num % 2 == 0: print("Even") else: print("Odd")Output:
EvenOddEvenOddIterate Over the Keys, Values, and Key-Value Pairs of Dictionaries
We can iterate over the keys, values, and key-value pairs of a dictionary by calling specific dictionary methods. Let's see how.
To iterate over thekeys, we write:
for <var> in <dictionary_variable>: <code>We just write the name of the variable that stores the dictionary as the iterable.
💡 Tip:you can also write <dictionary_variable>.keys()but writing the name of the variable directly is more concise and it works exactly the same.
For example:
>>> my_dict = { "a": 1, "b": 2, "c": 3}>>> for key in my_dict: print(key)abc💡 Tip:you can assign any valid name to the loop variable.
To iterate over thevalues, we use:
for <var> in <dictionary_variable>.values(): <code>For example:
>>> my_dict = { "a": 1, "b": 2, "c": 3}>>> for value in my_dict.values(): print(value)123To iterate over thekey-value pairs, we use:
for <key>, <value> in <dictionary_variable>.items(): <code>💡 Tip:we are defining two loop variables because we want to assign the key and the value to variables that we can use in the loop.
>>> my_dict = { "a": 1, "b": 2, "c": 3}>>> for key, value in my_dict.items(): print(key, value)a 1b 2c 3If we define only one loop variable, this variable will contain a tuple with the key-value pair:
>>> my_dict = { "a": 1, "b": 2, "c": 3}>>> for pair in my_dict.items(): print(pair)('a', 1)('b', 2)('c', 3)Break and Continue in Python
Now you know how to iterate over sequences in Python. We also have loop control statements to customize what happens when the loop runs: breakand continue.
The Break Statement
The breakstatement is used to stop the loop immediately.
When a breakstatement is found, the loop stops and the program returns to its normal execution beyond the loop.
In the example below, we stop the loop when an even element is found.
>>> my_list = [1, 2, 3, 4, 5]>>> for elem in my_list: if elem % 2 == 0: print("Even:", elem) print("break") break else: print("Odd:", elem)Odd: 1Even: 2breakThe Continue Statement
The continuestatement is used to skip the rest of the current iteration.
When it is found during the execution of the loop, the current iteration stops and a new one begins with the updated value of the loop variable.
In the example below, we skip the current iteration if the element is even and we only print the value if the element is odd:
>>> my_list = [1, 2, 3, 4, 5]>>> for elem in my_list: if elem % 2 == 0: print("continue") continue print("Odd:", elem)Odd: 1continueOdd: 3continueOdd: 5The zip() function in Python
zip()is an amazing built-in function that we can use in Python to iterate over multiple sequences at once, getting their corresponding elements in each iteration.
We just need to pass the sequences as arguments to the zip()function and use this result in the loop.
For example:
>>> my_list1 = [1, 2, 3, 4]>>> my_list2 = [5, 6, 7, 8]>>> for elem1, elem2 in zip(my_list1, my_list2): print(elem1, elem2)1 52 63 74 8The enumerate() Function in Python
You can also keep track of a counter while the loop runs with the enum()function. It is commonly used to iterate over a sequence and get the corresponding index.
💡 Tip:By default, the counter starts at 0.
For example:
>>> my_list = [5, 6, 7, 8]>>> for i, elem in enumerate(my_list): print(i, elem)0 51 62 73 8>>> word = "Hello">>> for i, char in enumerate(word): print(i, char)0 H1 e2 l3 l4 oIf you start the counter from 0, you can use the index and the current value in the same iteration to modify the sequence:
>>> my_list = [5, 6, 7, 8]>>> for index, num in enumerate(my_list): my_list[index] = num * 3>>> my_list[15, 18, 21, 24]You can start the counter from a different number by passing a second argument to enumerate():
>>> word = "Hello">>> for i, char in enumerate(word, 2): print(i, char)2 H3 e4 l5 l6 oThe else Clause
For loops also have an elseclause. You can add this clause to the loop if you want to run a specific block of code when the loop completes all its iterations without finding the breakstatement.
💡 Tip:if breakis found, the elseclause doesn't run and if breakis not found, the elseclause runs.
In the example below, we try to find an element greater than 6 in the list. That element is not found, so breakdoesn't run and the elseclause runs.
my_list = [1, 2, 3, 4, 5]for elem in my_list: if elem > 6: print("Found") breakelse: print("Not Found")The output is:
Not FoundHowever, if the breakstatement runs, the elseclause doesn't run. We can see this in the example below:
my_list = [1, 2, 3, 4, 5, 8] # Now the list has the value 8for elem in my_list: if elem > 6: print("Found") breakelse: print("Not Found")The output is:
Found🔹 While Loops in Python
While loops are similar to for loops in that they let us repeat a block of code. The difference is that while loops run while a condition is True.
In a while loop, we define the condition, not the number of iterations. The loop stops when the condition is False.
This is the general syntax of a while loop:
while <condition>: <code>💡 Tip:in while loops, you must update the variables that are part of the condition to make sure that the condition will eventually become False.
For example:
>>> x = 6>>> while x < 15: print(x) x += 167891011121314>>> x = 4>>> while x >= 0: print("Hello" * x) x -= 1HelloHelloHelloHelloHelloHelloHelloHelloHelloHello>>> num = 5>>> while num >= 1: print("*" * num) num -= 2More From This Topic
View Topic
Front End JavaScript Development Handbook – React, Angular, and Vue Compared
Frontend frameworks are indispensable in web development. They provide structured approaches and pre …
How to Deploy a Serverless Spam Classifier Using Scikit
In today's digital world, spam is no longer just an annoyance - it's a growing security threat. To c …
How to Clean Time Series Data in Python
Real-world time series data is rarely clean. Sensors drop out, systems clock-drift, pipelines duplic …
How to Build a Fashion App That Helps You Organize Your Wardrobe
I used to spend too long deciding what to wear, even when my closet was full.That frustration made t …
How to Build a PostgreSQL
June 9, 2026 / #Po …
How to Build Optimal AI Agents That Actually Work – A Handbook for Devs
Since moving to Silicon Valley in 2025, I've seen AI everywhere. And after I attended NVIDIA GTC 202 …